package com.hsd.whb.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-09-08 19:28:05
 */
public class OneStreamToManyStream extends InputStream {

    private InputStream inputStream;

    private List<BlockInputStream> streams;

    public OneStreamToManyStream(InputStream inputStream, int size) {
        this.inputStream = inputStream;
        this.streams = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            streams.add(new BlockInputStream());
        }
    }

    public OneStreamToManyStream(InputStream inputStream, int size, int buffSize) {
        this.inputStream = inputStream;
        this.streams = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            streams.add(new BlockInputStream(buffSize));
        }
    }


    @Override
    public int read() throws IOException {
        int length = inputStream.read();
        if (length == -1) {
            finish();
        } else {
            write(length, null, 0, length);
        }
        return length;
    }

    @Override
    public int read(byte[] b) throws IOException {
        int length = inputStream.read(b);
        if (length == -1) {
            finish();
        } else {
            write(length, b, 0, length);
        }
        return length;
    }


    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int length = inputStream.read(b, off, len);
        if (length == -1) {
            finish();
        } else {
            write(length, b, off, length);
        }
        return length;
    }

    public List<BlockInputStream> getStreams() {
        return streams;
    }

    public void setStreams(List<BlockInputStream> streams) {
        this.streams = streams;
    }

    @Override
    public int available() {
        try {
            return inputStream.available();
        } catch (IOException e) {
            return 0;
        }
    }

    private void finish() {
        streams.parallelStream().forEach((BlockInputStream stream) -> stream.setFinish(true));
    }

    private void write(int a, byte[] b, int off, int len) {
        streams.parallelStream().forEach((BlockInputStream stream) -> {
            if (b != null) stream.write(b, off, len);
            else stream.write(a);
        });
    }

    public static void main(String[] args) throws Exception {

    }
}
